import pandas as pd
from MyTT import *
import akshare as ak
import numpy as np
import os
from datetime import datetime
from sqlalchemy import create_engine, distinct, or_, and_
import backtrader as bt
import pymssql
from urllib.parse import quote_plus as urlquote
from configparser import ConfigParser
import warnings
import pyfolio as pf

warnings.filterwarnings("ignore")

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

conf = ConfigParser()
conf.read('env.ini')

sqlserver = ('sqlserver_out', 'sqlserver_in')[0]

host = conf.get(sqlserver, 'host')
port = conf.get(sqlserver, 'port')
user = conf.get(sqlserver, 'user')
password = conf.get(sqlserver, 'password')
schema = conf.get(sqlserver, 'schema')
db_name = conf.get(sqlserver, 'db')


# 我们使用的时候，直接用我们新的类读取数据就可以了。
class price_momentum(bt.Strategy):
    params = (('period', 10), ('hold_percent', 0.1), ('printlog', False),)

    def __init__(self):
        self.order = None
        self.daily_pnl = dict()
        self.trade_info = list()
        # Keep a reference to the "close" line in the data[0] dataseries
        self.bar_num = 0
        # 保存现有持仓的股票
        self.position_dict = {}
        # 当前有交易的股票
        self.stock_dict = {}
        self.cache_log = list()

    def log(self, txt, dt=None, doprint=True):
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            # print(f'{dt.isoformat()},{txt}')
            print(txt)
            self.cache_log.append(txt)

    # def prenext(self):
    #
    #     self.next()

    def next(self):
        # 假设有100万资金，每次成份股调整，每个股票使用1万元
        self.bar_num += 1
        # 前一交易日和当前的交易日
        pre_date = self.datas[0].datetime.date(-1).strftime("%Y%m%d")
        current_date = self.datas[0].datetime.date(0).strftime("%Y%m%d")
        dt = int(current_date)

        if dt not in self.daily_pnl:
            # item = [dt, self.broker.getvalue() - init_cash]
            self.daily_pnl[dt] = round(self.broker.getvalue() - init_cash, 2)

        # 总的价值
        total_value = self.broker.getvalue()
        total_cash = self.broker.getcash()
        # self.log(f"total_value : {total_value}->bar num={self.bar_num}->close_len={len(self.data.close)}->x1={self.data[0]}->x2={self.data.close[0]}")
        # 第一个数据是指数，校正时间使用，不能用于交易
        # 循环所有的股票,计算股票的数目

        # 计算理论上的手数
        # now_value = total_value / int(total_target_stock_num * self.p.hold_percent * 2)
        total_target_stock_num = len(self.datas[1:])
        now_value = total_value / total_target_stock_num

        # 如果今天是调仓日
        if self.bar_num % self.p.period == 0:
            # 循环股票，平掉所有的股票，计算现在可以交易的股票的累计收益率
            result = []
            for data in self.datas[1:]:
                data_date = data.datetime.date(0).strftime("%Y%m%d")

                # 已经下单，但是订单没有成交
                # if data._name in self.position_dict and pos == 0:
                #     order = self.position_dict[data._name]
                #     self.cancel(order)
                #     self.position_dict.pop(data._name)
                    # 如果两个日期相等，说明股票在交易,就计算收益率，进行排序
                if current_date == data_date:
                    close_info = data.close
                    if len(close_info) >= self.p.period:
                        now_close = close_info[0]
                        pre_close = close_info[-self.p.period + 1]
                        cumsum_rate = (now_close - pre_close) / pre_close
                        result.append([data, cumsum_rate])

            # 根据计算出来的累计收益率进行排序，选出前10%的股票做多，后10%的股票做空
            new_result = sorted(result, key=lambda x: x[1])
            num = int(self.p.hold_percent * total_target_stock_num)
            sell_list = new_result[:num]
            buy_list = new_result[-num:]
            # 根据计算出来的信号，买卖相应的股票
            for data, cumsum_rate in buy_list:
                code = data._name
                data_date = data.datetime.date(0).strftime("%Y%m%d")
                if data_date != current_date:
                    print(f'{code} continue')
                    continue
                pos = self.getposition(data).size
                if not pos:
                    lots = now_value / data.close[0]
                    lots = int(lots / 100) * 100  # 计算能下的手数，取整数
                    self.order = self.buy(data, size=lots, name=code)
                    # self.position_dict[code] = self.order

            for data, cumsum_rate in sell_list:
                code = data._name
                if data_date != current_date:
                    print(f'{code} continue')
                    continue
                pos = self.getposition(data).size
                if pos:
                    self.order = self.close(data, name=code)
                    print(f'sell_code={code}')
                    # self.position_dict[code] = self.order

    def notify_order(self, order):
        # 未被处理的订单
        if order.status in [order.Submitted, order.Accepted]:
            return
        # 已经处理的订单
        if order.status in [order.Completed, order.Canceled, order.Margin]:
            code = order.data._name
            if order.isbuy():
                self.log(
                    f'code={code} BUY CREATE TIME: {bt.num2date(order.created.dt)}, EXECUTED TIME: {bt.num2date(order.executed.dt)}')
                self.log(
                    'BUY EXECUTED, ref:%.0f，Price: %.2f, Cost: %.2f, Comm %.2f, Size: %.2f, Stock: %s' %
                    (order.ref,  # 订单编号
                     order.executed.price,  # 成交价
                     order.executed.value,  # 成交额
                     order.executed.comm,  # 佣金
                     order.executed.size,  # 成交量
                     code))  # 股票名称
                trade_dt = int(bt.num2date(order.created.dt).strftime('%Y%m%d%H%M%S'))
                trade_item = [trade_dt, code, 'BUY', round(order.executed.price, 2), order.executed.size,
                              round(order.executed.comm, 2)]
                self.trade_info.append(trade_item)
            else:  # Sell
                self.log(
                    f'code={code} SELL CREATE TIME: {bt.num2date(order.created.dt)}, EXECUTED TIME: {bt.num2date(order.executed.dt)}')
                self.log('SELL EXECUTED, ref:%.0f, Price: %.2f, Cost: %.2f, Comm %.2f, Size: %.2f, Stock: %s' %
                         (order.ref,
                          order.executed.price,
                          order.executed.value,
                          order.executed.comm,
                          order.executed.size,
                          code))
                trade_dt = int(bt.num2date(order.created.dt).strftime('%Y%m%d%H%M%S'))
                trade_item = [trade_dt, code, 'SELL', round(order.executed.price, 2),
                              order.executed.size, round(order.executed.comm, 2)]
                self.trade_info.append(trade_item)
            self.bar_executed = len(self)

        # Write down: no pending order
        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return

        self.log("OPERATION PROFIT, GROSS %.2f, NET %.2f" % (trade.pnl, trade.pnlcomm))

    def stop(self):
        print('Strategy Finish!!!')

        with open(r'C:\Users\AndrewX\Desktop\cache_log.txt', 'w') as f:
            res = '\n'.join(self.cache_log)
            f.write(res)

        daily_pnl_df = pd.DataFrame(self.daily_pnl.items(), columns=['DATE_T', 'PNL'])
        append_df = pd.DataFrame([[101, round((self.broker.getvalue() / init_cash - 1) * 100, 2)]],
                                 columns=['DATE_T', 'PNL'])
        daily_pnl_df = daily_pnl_df.append(append_df, ignore_index=True)
        trade_df = pd.DataFrame(self.trade_info, columns=['DATE_T', 'STK_CODE', 'ACTION', 'PRICE', 'AMOUNT', 'COMM'])
        pnl_table = 'TEST_DAILY_PNL'
        trade_table = 'TEST_TRADE_INFO'
        # daily_pnl_df = daily_pnl_df.loc[(daily_pnl_df['DATE_T'] >= 20230428) | (daily_pnl_df['DATE_T'] == 101)]
        insert_db(trade_df, trade_table)
        insert_db(daily_pnl_df, pnl_table)
        print('insert table ok')


def get_stocks(index):
    sql = f"SELECT DISTINCT CONSTITUENT_CODE FROM index_constituent WHERE INDEX_CODE='{index}'"
    r = exec_sql(sql)
    stocks = [tok[0] for tok in r if tok[0][:2] not in ('30', '68')]
    # stocks = ['300122', '600809']

    return stocks


def get_data(stocks, freq='day'):
    if freq == '1min':
        table_name = 'STOCK_MIN_DATA'
    elif freq == '15min':
        table_name = 'STOCK_15MIN_DATA'
    else:
        table_name = 'STOCK_DAY_DATA'

    test_code = '399300'
    # stocks.append('000877')
    stocks.append(test_code)
    stocks_str = ','.join(f"'{tok}'" for tok in stocks)
    sql = f"SELECT * FROM {table_name} WHERE code in ({stocks_str})"
    r = exec_sql(sql)
    df = pd.DataFrame(r, columns=['code', 'datetime', 'close', 'open', 'low', 'high', 'volume', 'money'])
    df['datetime'] = df['datetime'].map(time_map)
    sql2 = f"SELECT COUNT(1) FROM {table_name} WHERE code='{test_code}'"
    r2 = exec_sql(sql2)
    test_count = r2[0][0]
    res = dict()

    for code in stocks:
        sig_df = df.loc[df['code'] == code]
        print(f'code={code}->len={len(sig_df)}->test_count={test_count}')
        if len(sig_df) == test_count or code == test_code:
            sig_df.sort_values('datetime', inplace=True, ignore_index=True)
            sig_df.set_index('datetime', inplace=True)
            res[code] = sig_df
    return res


def exec_sql(sql):
    conn = pymssql.connect(host=host, port=port, user=user, password=password, database=db_name)
    cursor = conn.cursor()
    cursor.execute(sql)
    r = cursor.fetchall()
    cursor.close()
    conn.close()
    return r


def time_map(x):
    t = datetime.strptime(str(x), '%Y%m%d%H%M')
    return t


def insert_db(df, table_name):
    yconnect = create_engine(f'mssql+pymssql://{user}:{urlquote(password)}@{host}:{port}/{db_name}?charset=utf8')
    pd.io.sql.to_sql(df, table_name, yconnect, schema=schema, if_exists='append', index=False)


pre_ratio = 0.0048
ratio = 0.1
trail_ratio = 0.035
count_info = dict()
# stocks = get_stocks()
init_cash = 1e8


def run_backtrade(stocks, index):
    cerebro = bt.Cerebro()

    data_all = get_data(stocks)
    data0 = data_all[index]
    datafeed0 = bt.feeds.PandasData(dataname=data0)
    cerebro.adddata(datafeed0, name=f'{index}')

    for code in data_all:
        if code == index:
            continue
        data = data_all[code]

        datafeed = bt.feeds.PandasData(dataname=data)
        # st_date = datetime(2023, 1, 1)
        # ed_date = datetime(2023, 6, 16)
        # datafeed = bt.feeds.PandasData(dataname=data, fromdate=st_date, todate=ed_date)
        cerebro.adddata(datafeed, name=f'{code}')
        print(f'{code} feeds ok')

    ##   st_date = datetime.datetime(2023, 3, 1)
    ##ed_date = datetime.datetime(2023, 6, 5)

    # 初始资金 100,000,0
    cerebro.broker.setcash(init_cash)
    # 佣金，双边各 0.0003
    cerebro.broker.setcommission(commission=0.0003)
    # 滑点：双边各 0.0001
    cerebro.broker.set_slippage_perc(perc=0.0001)

    cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='pnl')  # 返回收益率时序数据
    cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='_AnnualReturn')  # 年化收益率
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='_SharpeRatio')  # 夏普比率
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name='_DrawDown')  # 回撤

    cerebro.addstrategy(price_momentum)

    result = cerebro.run()
    strat = result[0]
    # 返回日度收益率序列
    daily_return = pd.Series(strat.analyzers.pnl.get_analysis())
    # 打印评价指标
    print("--------------- TimeReturn -----------------")
    print(daily_return)
    print("--------------- AnnualReturn -----------------")
    print(strat.analyzers._AnnualReturn.get_analysis())
    print("--------------- SharpeRatio -----------------")
    print(strat.analyzers._SharpeRatio.get_analysis())
    print("--------------- DrawDown -----------------")
    print(strat.analyzers._DrawDown.get_analysis())
    # cerebro.plot()


def main():
    index = '399300'
    stocks = get_stocks(index)
    run_backtrade(stocks, index)


if __name__ == '__main__':
    main()
